package DD6;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class IteratorTest {
	public static void main(String[] args) {
		IteratorTest t1 = new IteratorTest();
		//t1.test1();
		//t1.WrongWay1(); //Wrong way 1 test
		//t1.WrongWay2(); //Wrong way 2 test
		t1.Del();
	}

	public void test1() {
		Collection coll = new ArrayList(); 
		coll.add(123);
		coll.add(456);
		coll.add(new String("Tom"));
		coll.add(false);

		Iterator iterator = coll.iterator();
// way 1
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//way 2 
//        for(int i = 0;i < coll.size();i++){
//            System.out.println(iterator.next());
//        }
// other two way to show the element in this collection by order
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		// best way
	}

	public void WrongWay1() {

		Collection coll = new ArrayList();
		coll.add(123);
		coll.add(456);
		coll.add(789);
		coll.add("hhh");
		coll.add(true);
        Iterator iterator = coll.iterator();
//        while((iterator.next()) != null){
//            System.out.println(iterator.next());
//        }

		while (coll.iterator().hasNext()) {
			System.out.println(coll.iterator().next());
		}
//When using this way, every time it creates a new object and the program will abidingly print the first element
	}
	public void WrongWay2() {

		Collection coll = new ArrayList();
		coll.add(123);
		coll.add(456);
		coll.add(789);
		coll.add("hhh");
		coll.add(true);
        Iterator iterator = coll.iterator();
        while((iterator.next()) != null){
            System.out.println(iterator.next());
        }

		/*
		 * When the program checks whether or not this collection “has next", it
		 * actually will move the pointer down, so it will skip the element that it
		 * checked and print the next element.
		 */	}

	public void Del() {
		Collection coll = new ArrayList();
		coll.add("123");
		coll.add(456);
		coll.add(new String("Tom"));
		coll.add(false);

		Iterator iterator = coll.iterator();
		while (iterator.hasNext()) {
//            iterator.remove();
			Object obj = iterator.next();
			if ("123".equals(obj)) {
				iterator.remove();
			}
			if ("Tom".equals(obj)) {
				iterator.remove();
//                iterator.remove();
			}

		}
		iterator = coll.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}
}
